<template>
  <!-- 公司设置 -->
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs v-model="activeName" v-loading="loading">
          <el-tab-pane label="角色管理" name="first">
            <!-- 新增角色按钮 -->
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="RolesIsShow = true"
              :disabled="!$chenkPerm('point-add')"
            >
              新增角色
            </el-button>
            <div
              style="
                border-top: 1px transparent solid;
                width: 100%;
                margin: 5px 0;
              "
            ></div>
            <!-- 角色渲染表格 -->
            <el-table :data="tableData" border style="width: 100%">
              <el-table-column
                type="index"
                :index="indexMethod"
                label="序号"
                width="130"
              >
              </el-table-column>
              <el-table-column prop="name" label="名称" width="180">
              </el-table-column>
              <el-table-column prop="description" label="描述">
              </el-table-column>
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button
                    type="success"
                    size="small"
                    @click="handlePerm(row.id)"
                    >分配权限</el-button
                  >
                  <el-button
                    type="primary"
                    size="small"
                    @click="editRoles(row.id)"
                    >编辑</el-button
                  >
                  <el-button
                    type="danger"
                    size="small"
                    @click="delRoles(row.id)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <!-- 新增角色弹层 -->
            <el-dialog
              :title="rolesObj.name ? '编辑角色' : '新增角色'"
              :visible.sync="RolesIsShow"
              width="40%"
              @close="handleSwitch"
            >
              <el-form
                ref="form"
                :rules="rules"
                :model="rolesObj"
                label-width="80px"
              >
                <el-form-item label="角色名称" style="width: 120" prop="name">
                  <el-input
                    v-model="rolesObj.name"
                    placeholder="输入角色名称"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  label="角色描述"
                  style="width: 120"
                  prop="description"
                >
                  <el-input
                    v-model="rolesObj.description"
                    placeholder="输入角色描述"
                  ></el-input>
                </el-form-item>
              </el-form>
              <template #footer>
                <el-button @click="handleSwitch" size="small">取 消</el-button>
                <el-button type="primary" @click="handleRoles" size="small"
                  >确 定</el-button
                >
              </template>
            </el-dialog>
            <!-- 分页 -->
            <el-pagination
              style="text-align: center; margin-top: 10px"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="query.page"
              :page-sizes="[5, 10, 15, 20]"
              :page-size="query.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
            >
            </el-pagination>
            <!-- 分配权限弹框 -->
            <el-dialog
              title="分配权限"
              :visible="showAssginClose"
              @close="handleAssginClose"
            >
              <!-- 
                设置或获取tree组件选中的节点，
                  有2种方式
                    1，通过 node(节点对象)方式
                    2，通过 key 的方式，需要给tree添加node-key属性
                代码中: 可以通过 this;$refs.treeRef 获取到tree组件对象，
                调用方法1，获取: getCheckedNodes() / getCheckdeKeys()
                      2，设置: setCheckedNodes([]) / setcheckedKeys([])
               -->
              <el-tree
                :data="permList"
                :props="{ label: 'name' }"
                show-checkbox
                node-key="id"
                ref="tree"
                default-expand-all
                check-strictly
              />
              <template #footer>
                <el-button @click="handleAssginClose">取消</el-button>
                <el-button type="primary" @click="handleAssginAdd"
                  >确定</el-button
                >
              </template>
            </el-dialog>
          </el-tab-pane>
          <!-- 公司信息 -->
          <el-tab-pane label="公司信息" name="second">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              :closable="false"
              show-icon
            >
            </el-alert>
            <el-form disabled label-width="180px" style="margin-top: 20px">
              <el-form-item label="公司名称">
                <el-input v-model="company.name" style="width: 80%" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="company.companyAddress" style="width: 80%" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="company.mailbox" style="width: 80%" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="company.remarks" style="width: 80%" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script>
import {
  getParsonasApi,
  addParsonasApi,
  delParsonasApi,
  getRolesParsonasApi,
  updatedParsonasApi,
  getCompanyDetailApi,
  putPermParsonasApi,
} from "@/api/persona";
import { getPermissionsApi } from "@/api/permissions";
import { list2Tree } from "@/utils/shift";
export default {
  name: "ViewsSetting",
  data() {
    return {
      // 收集激活的tab栏
      activeName: "first",
      // 角色列表
      tableData: [],
      // 数据总条数
      total: 0,
      // 查询参数
      query: {
        page: 1,
        pagesize: 5,
      },
      // 控制弹层开关
      RolesIsShow: false,
      // 收集用户输入的值
      rolesObj: {
        name: "",
        description: "",
      },
      rules: {
        name: [{ required: true, message: "角色必填", trigger: "blur" }],
        description: [{ required: true, message: "描述必填", trigger: "blur" }],
      },
      loading: false,
      // 公司表单对象
      company: {
        name: "",
        mailbox: "",
        remarks: "",
        companyAddress: "",
      },
      // 分配权限
      showAssginClose: false,
      permList: [],
    };
  },
  created() {
    this.getParsonas();
  },
  methods: {
    // 打开分配权限弹层
    async handlePerm(id) {
      this.id = id;
      // 打开弹层
      this.showAssginClose = true;
      // 请求权限列表
      const resp = await getPermissionsApi();
      // 将数据转成树形结构
      this.permList = list2Tree(resp.data, "0");
      // 回显
      const { data } = await getRolesParsonasApi(id);
      this.$refs.tree.setCheckedKeys(data.permIds);
    },
    // 分配权限
    async handleAssginAdd() {
      const permIds = this.$refs.tree.getCheckedKeys();
      try {
        await putPermParsonasApi({
          id: this.id,
          permIds,
        });
        this.handleAssginClose();
        this.$message.success("分配成功");
      } catch (error) {
        this.$message.error(error.message || "操作失败");
      }
    },
    // 关闭分配权限弹层
    handleAssginClose() {
      this.showAssginClose = false;
      // 清空tree组件
      this.$refs.tree.setCheckedKeys([]);
    },
    //获取角色信息
    async getParsonas() {
      this.loading = true;
      const { data } = await getParsonasApi(this.query);
      this.total = data.total;
      this.tableData = data.rows;
      this.loading = false;
    },
    // 新增角色
    handleRoles() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return;
        if (!this.rolesObj.id) {
          // 提交新增
          await addParsonasApi(this.rolesObj);
        } else {
          // 提交修改
          await updatedParsonasApi(this.rolesObj);
        }

        this.getParsonas();
        this.handleSwitch();
      });
    },
    // 关闭弹层
    handleSwitch() {
      this.rolesObj = {
        name: "",
        description: "",
      };
      this.RolesIsShow = false;
      this.$refs.form.resetFields();
    },
    // 删除角色
    async delRoles(id) {
      // 调用删除接口
      try {
        await this.$confirm("此操作将永久删除该角色, 是否继续?", "温馨提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        // 判断 当前页数据只有一个数据时，删除之后显示上一页的数据
        if (this.tableData.length === 1 && this.query.page > 1) {
          this.query.page--;
        }
        await delParsonasApi(id);
        // 重新渲染页面
        this.getParsonas();
        this.$message.success("删除成功");
      } catch (error) {
        this.$message.success("取消成功");
      }
    },
    // 修改角色
    async editRoles(id) {
      const { data } = await getRolesParsonasApi(id);
      this.rolesObj = {
        ...data,
      };
      this.RolesIsShow = true;
    },
    // 处理分页变化
    handleCurrentChange(val) {
      // 把选择的页数同步到query.page里
      this.query.page = val;
      this.getParsonas();
    },
    // 处理条数变化
    handleSizeChange(val) {
      // 把选择的条数同步到query.pagesize里
      this.query.pagesize = val;
      this.getParsonas();
    },
    //处理序号
    indexMethod(index) {
      return (this.query.page - 1) * this.query.pagesize + index + 1;
    },
  },
  watch: {
    async activeName(val) {
      if (val !== "second") return;
      if (this.company.id) return;
      const { data } = await getCompanyDetailApi(
        this.$store.getters.userInfo.companyId
      );
      this.company = data;
    },
  },
};
</script>

<style>
</style>